package com.lw.leetcode.arr.b;

/**
 * Created with IntelliJ IDEA.
 * 904. 水果成篮
 *
 * @author liw
 * @version 1.0
 * @date 2021/12/5 16:40
 */
public class TotalFruit {

    public static void main(String[] args) {
        TotalFruit test = new TotalFruit();

        // 5
//        int[] arr = {3,3,3,1,2,1,1,2,3,3,4};

        // 7
        int[] arr = {3, 3, 3, 1, 2, 1, 1, 2, 3, 3, 4, 3, 4, 3, 4};

        int i = test.totalFruit(arr);
        System.out.println(i);
    }

    public int totalFruit(int[] fruits) {
        int max = 0;
        int v1 = fruits[0];
        int c1 = 1;
        int v2 = -1;
        int c2 = 0;
        int st = 0;
        int end = 1;
        int length = fruits.length;
        while (end < length) {
            int v = fruits[end];
            if (v == v1) {
                c1++;
            } else if (v == v2) {
                c2++;
            } else {
                max = Math.max(max, c1 + c2);
                while (c1 != 0 && c2 != 0) {
                    int f = fruits[st];
                    if (f == v1) {
                        c1--;
                    } else {
                        c2--;
                    }
                    st++;
                }
                if (c1 == 0) {
                    v1 = v;
                    c1 = 1;
                } else {
                    v2 = v;
                    c2 = 1;
                }
            }
            end++;
        }
        return Math.max(max, c1 + c2);
    }

}
